<?php
/**
 * PddCopyProducts.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2021/1/17- 下午4:34
 */

namespace common\jobs\models;


use common\jobs\services\SyncEsService;
use common\models\pdd\PddCopyProducts as BasePddCopyProducts;
use yii\helpers\FileHelper;
use Yii;

class PddCopyProducts extends BasePddCopyProducts
{


    /**
     * 自动录入新增和修改时间
     * @return mixed
     */
    public function beforeValidate()
    {
        $timestamp = time();
        if($this->getIsNewRecord())
        {
            $this->created_at = $timestamp;
            $this->updated_at = $timestamp;
        }else{
            $this->updated_at = $timestamp;
        }
        return parent::beforeValidate();
    }

    /**
     * 数据变更后同步es
     * @param bool $insert
     * @param array $changedAttributes
     * @throws \yii\base\Exception
     */
//    public function afterSave($insert, $changedAttributes)
//    {
//        if (!Yii::$app->db->isActive) {
//            Yii::$app->db->open();
//        }
//        parent::afterSave($insert, $changedAttributes);
//        $this->writeSpiderLog($this->id."这个id传入成功");
//        if ($this->id) {
//            $syncEsService = new SyncEsService();
//            $syncEsService->syncCopyProducts([$this->id]);
//        }
//        $this->writeSpiderLog($this->id."这个id更新成功");
//        Yii::$app->db->close();
//    }

    /**
     * 文件日志记录
     * @param $msg
     * @throws ServicesException
     */
    public function writeSpiderLog($msg)
    {

        $path = Yii::getAlias('@runtime/api/spider_crawler_execule_update_es_id/');

        //目录如果不存就先创建目录
        if (!is_dir($path)) {
            FileHelper::createDirectory($path);
        }

        $cp = fopen($path . 'log-' . date('Ymd H:i') . '.log', "a+");
        $txt = "【" . date('Y-m-d H:i:s', time()) . "】---" . $msg . "\r\n";
        fwrite($cp, $txt);
        fclose($cp);

    }

}
